package org.farm2.service.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.farm2.files.domain.ResourceFile;
import org.farm2.files.service.ResourceFileServiceInter;
import org.farm2.service.inter.WebResourceServiceInter;
import org.farm2.skc.domain.SkcKnow;
import org.farm2.skc.dto.web.WebKnowDto;
import org.farm2.skc.service.SkcKnowServiceInter;
import org.farm2.tools.db.commons.FarmUUID;
import org.farm2.tools.web.Farm2HtmlUtils;
import org.farm2.tools.web.Farm2HttpUtils;
import org.farm2.tools.web.FarmResponseCode;
import org.farm2.tools.web.FarmResponseResult;
import org.farm2.tools.web.domain.WebDoc;
import org.farm2.tools.web.dto.IdDto;
import org.farm2.tools.web.dto.UrlDto;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 知识
 *
 * @author cbtg自动生成  2025-2-4 12:13:51
 */
@RestController
@RequestMapping("/api/webpage")
@Slf4j
public class WebDownloadWebPageController {
    @Autowired
    private SkcKnowServiceInter skcKnowServiceImpl;

    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;

    @Autowired
    private WebResourceServiceInter webResourceService;
    /**
     * 下载web页面
     *
     * @param url
     * @return
     */
    @PreAuthorize("@farmAction.has('skcKnow.add')")
    @PostMapping
    public FarmResponseResult addSubmit(@Valid @RequestBody UrlDto url) {
        if (Farm2HttpUtils.isHasIpOrPort(url.getUrl()) || !Farm2HttpUtils.isUrl(url.getUrl())) {
            return FarmResponseResult.getInstance(FarmResponseCode.ERROR, "请检查url格式", null);
        }
        WebDoc doc = webResourceService.downloadWebPage(url.getUrl());
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, doc);
    }
}
